import os
import re
import shutil
import xml.etree.ElementTree as ET
import zipfile
from pandas.core import frame as pd


# Copyright 2021 The SuningBank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#auth 16080951

class Util:
    def __init__(self):
        self.config = {
            "tmp_path":"..\\tmp",
            "result_path":"..\\result"
        }

    def rename_file_to_zip(self, filename, suffix='.zip') -> object:
        portion = os.path.splitext(filename)
        file_suffix = str(portion[1]).lower()
        if file_suffix == ".xps":
            newname = portion[0] + suffix
            os.rename(filename, newname)
            return newname
        else:
            print("please input the correct file end with .xps")
        return 0

    def unzip_file(self, fz_name, path):
        """
        解压缩文件
        :param fz_name: zip文件
        :param path: 解压缩路径
        :return:
        """
        flag = False

        if zipfile.is_zipfile(fz_name):  # 检查是否为zip文件
            with zipfile.ZipFile(fz_name, 'r',compression=zipfile.ZIP_DEFLATED) as zipf:
                zipf.extractall(path)
                # for p in zipf.namelist():
                #     # 使用cp437对文件名进行解码还原， win下一般使用的是gbk编码
                #     p = p.encode('cp437').decode('gbk')  # 解决中文乱码
                #     print(fz_name, p,path)
                flag = True

        return {'file_name': fz_name, 'flag': flag}

    def getFileNames(self, path):
        self.L = []
        for root, dirs, files in os.walk(path):
            for file in files:
                if root.find("_rels") >= 0:
                    continue
                if file.find(".rels") >= 0:
                    continue
                if file.find('[0].piece') >= 0:
                    self.L.append(os.path.join(root, file))
        return self.L


    def moveToResult(self):
        self.mkdir(self.config['result_path'])
        for root,dirs,files in os.walk("./"):
            for file in files:
                if file.find("xlsx") >= 0:
                    self.move(os.path.join(root,file),self.config['result_path'])
                    #print(file)



    def doExcel(self,element,title,fileNameNoKZ):
        df = pd.DataFrame(element, columns=title)
        df.to_excel(fileNameNoKZ+'.xlsx', index=0)




    def remove(self,path):
        try:
            shutil.rmtree(path)
        except:
            pass

    def move(self,src,dest):
        shutil.move(src,dest)

    def toStr(self,array):
        return "".join(array).replace("|","")

    def mkdir(self,path):
        # 引入模块
        import os

        # 去除首位空格
        path = path.strip()
        # 去除尾部 \ 符号
        path = path.rstrip("\\")

        # 判断路径是否存在
        # 存在     True
        # 不存在   False
        isExists = os.path.exists(path)

        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            # 创建目录操作函数
            os.makedirs(path)

            print
            path + ' 创建成功'
            return True
        else:
            # 如果目录存在则不创建，并提示目录已存在
            print
            path + ' 目录已存在'
            return False